#!/bin/bash
# 
# Autor: Ricardo Brito do Nascimento
# Email: rbrito1978-blessed@yahoo.com.br
# Data: 20080404
# Versão: 1
#

ER_EMAIL="^[A-Za-z0-9_.-]+@([A-Za-z0-9_]+\.)+[A-Za-z]{2,4}$"
ER_SMTP="^[A-Za-z0-9-]+(([A-Za-z0-9_]+\.)+[A-Za-z]{2,4})?$"
ER_NUM="^([1-9]|[1-9][0-9]{1,3})$"
PORT=25

_uso(){
echo "os parametros são necessários!
	 ./$(basename $0) from; to; smtp-server;  msg; subject; port-sender
"
}

_sendmail(){
#echo "-----verifica se há os parametros necessários --------"
#echo "---- $# -----"
  if [ $# -lt 3 ]; then _uso; exit 0; fi
 
#echo "-----verifica o email do 'from' ------"
  from="ricardo@rbncurriculo.cjb.net"
  [ -z `echo $1|grep -oE $ER_EMAIL` ] && echo "email 'from' $1 inválido!" && exit 0;
  from=`echo $1|grep -oE $ER_EMAIL`
  

#echo "-----verifica o email do 'to' ------"
  to="ricardo@rbncurriculo.cjb.net"
  [ -z `echo $2|grep -oE $ER_EMAIL` ] && echo "email 'from' $2 inválido!" && exit 0;
  to=`echo $2|grep -oE $ER_EMAIL`

#echo "-----verifica o 'smtp-server' ------"
# server="mail.google.com"
  [ -z `echo $3|grep -oE $ER_SMTP` ] && echo "servidor SMTP 'smtp-server' $3 inválido!" &&  exit 0;
  server=`echo $3|grep -oE $ER_SMTP`
  
#echo "----Verifica a existencia do arquivo----"
  body="`ls -lhF`"
  [ $# -ge 4 ] && [ ! -z $4 ] && [ -e $4 ] && body=`cat $4`
#  [ $# -eq 5 ] && [ ! -z $4 ] && [ -e $4 ] && body=`cat $4`

#echo "-----verifica o subject ------"
  subject="::logs de backup::"
  [ $# -ge 5 ] && [ ! -z $5 ] && subject=$5

#echo "-----verifica porta de envio do servidor SMTP ------"
  [ $# -ge 6 ] && [ ! -z `echo $6|grep -oE $ER_NUM` ] && PORT=$6

#echo "----Configura a data de envio----"
  date=`LC_ALL=C date "+%a, %d %b %Y %k:%M:%S %z"`

  {
    sleep 1
    echo "EHLO $HOSTNAME"
    sleep 1
    echo "MAIL FROM: $from"
    sleep 1
    echo "RCPT TO: $to"
    sleep 1
    echo "DATA"
    sleep 1
    echo "FROM: $from"
    echo "TO: $to"
    echo "SUBJECT: $subject"
    echo "Date: $date"
    echo
    echo "$body"
    echo "."
    sleep 1
    echo "quit"
  }  | telnet $server $PORT
}

#_sendmail $@
